/*
*经销商新建合同产品 将客户信用期信用额带入到经销商合同
*/
public without sharing class DealerContractProductController {
	public List<ProductBean> pbList { get; set; }//产品列表
    public List<ContractProductBean> cpbList { get; set; }///合同产品列表
    public Contract__c con ;//当前的合同
    public Contract__c parentCon ;//总部合同
    
    
    public String cId { get; private set; }  // 合同的Id
    public String type { get; private set; }///类型

    public Boolean isSystem {get;private set;}//是否为分支机构

    public List<SelectOption> cate0Opts { get; private set; }
    public List<SelectOption> cate1Opts { get; private set; }
    
    //搜索用的字段
    public String name { get; set; }
    public String brand { get; set; }
    public String serial { get; set; }
    public String category0 { get; set; }
    public String category1 { get; set; }
    public String typeName {get;set;}
    
    public User u;
    private Map<Id,PriceBean> prMap ;//价格
    public Boolean Approve {get;set;}

    public String  cpbListJson {get;set;}///合同产品
    public String  productListJson {get;set;}
    public String corpcode; ///公司编码
    public String msg {get;set;}//消息;
    public Boolean isSuccess {get;private set;}//保存成功
    public String resJson {get;set;}///保存的json 
    public String parentconId;//分支机构总部合同id ;
    
    public Boolean isOption {get;set;} //是否为操作状态

    public String sealflag ;//封存标记
    public String concode ;

    public List<ContractProductBean> tempList { get; set; }///报价产品列表 临时操作的
    public String tempName {get;set;}//名称
    public String tempCategory1 {get;set;}//一级分类
    public String tempCategory2 {get;set;}//二级分类
    public String tempBrand {get;set;}//品牌
    public String tempTypeName {get;set;}//品牌
    public List<SelectOption> tempCategory1opts { get; private set; }//一级分类选项列表
    public List<SelectOption> tempCategory2opts { get; private set; }//二级分类选项列表
    public Boolean isSpecialAccount {get;set;}//是否为专票客户
    public Boolean isSaveSuccess {get;set;}//是否保存成功
    public DealerContractProductController(ApexPages.StandardController stdController) {

        cpbListJson = '[]';
        cId = stdController.getId();
        cId = cId == null ? System.currentPageReference().getParameters().get('cid'): cId;

        pbList  = new List<ProductBean>();
        prMap = new Map<Id ,PriceBean>();
        cpbList = new List<ContractProductBean>();
        tempList = new List<ContractProductBean>();


        isSaveSuccess = false;
        
        cate0Opts = new List<SelectOption>();
        cate0Opts.add(new SelectOption('', System.Label.Option_None));
        for (String str : System.Label.Product_Category0.split(',', -1)) {
            cate0Opts.add(new SelectOption(str, str));
        }

        cate1Opts = new List<SelectOption>();
        cate1Opts.add(new SelectOption('', System.Label.Option_None));
        for (String str : System.Label.Product_Category1.split(',', -1)) {
            cate1Opts.add(new SelectOption(str, str));
        }
    }
    public void init(){
    	con = [select Id,CompanyControls__c,CorpCode__c,Account__r.BillingType__c,Account__r.ParentId,Account__c,Status__c from Contract__c where id =:cid];
        isSystem = con.Account__r.ParentId == null ? false : true;
         System.debug('==='+ con.Account__r.ParentId);
        corpcode = con.Corpcode__c;

          ///获取封存标记
        Map<String,String> cm = getPicklistValues('Contract__c','Corpcode__c');
        concode = cm.get(con.CompanyControls__c);
         sealflag = 'Y-'+concode;

        Approve = (con.Status__c == '审批中'|| con.Status__c =='已生效') ? true : false;
        if(isSystem == true){
            List<Contract__c> cList =[select Id from Contract__c where Account__c =:con.Account__r.ParentId  and Status__c ='已生效' and Stopped__c != true order by createdDate desc limit 1];
            if(cList.size() > 0)parentCon =cList[0] ;
            System.debug('==='+ parentCon);
        }
        if(Test.isRunningTest()){
        
        }else{
       	u = [select SubCompany__c from User where Id = :UserInfo.getUserId()];
	    }
	    ///查询合同产品 
	    cpbListJson = getContractProduct(cid,false);
	    ///如果没有则查询去年的年度合同
	    if (cpbList.size() == 0) {
        	 ///查询有没有上年的年度合同
	        String lastYear = String.valueOf(Date.today().year() - 1);  //去年年份 
	       	List<Contract__c> lastCon = [select Id from Contract__c where Account__c =:con.Account__c and Year__c =:lastYear and Status__c = '已生效'   limit 1];
	       	if(lastCon.size() >0)cpbListJson = getContractProduct(lastCon[0].Id,true);
        }
      
    }
  
   //获得PickList的值
    public static Map<String, String> getPicklistValues(String sObjectName, String sFieldName){
        Map<String, String> picValues= new Map<String, String>();
        Map<String, Schema.SObjectType> sObjectDescribeMap = Schema.getGlobalDescribe();
        if (sObjectDescribeMap.containsKey(sObjectName)) {
            Map<String, Schema.SobjectField> sObjectFieldsMap = 
               sObjectDescribeMap.get(sObjectName).getDescribe().fields.getMap();
            if (sObjectFieldsMap.containsKey(sFieldName)) {
                Schema.DescribeFieldResult sObjectFieldDescribe = sObjectFieldsMap.get(sFieldName).getDescribe();
                List<Schema.PicklistEntry> lPickEntryList = sObjectFieldDescribe.getPicklistValues();
                for (Schema.PicklistEntry tPicklistEntry : lPickEntryList) {
                    if(tPicklistEntry.isActive() == true){
                        picValues.put(tPicklistEntry.getLabel(),tPicklistEntry.getValue());
                    }
                    /*picValues.put(tPicklistEntry.getValue(), new Map<String,object>{
                        'value' => tPicklistEntry.getValue(),
                        'isActive' => tPicklistEntry.isActive(),
                        'isDefaultValue' => tPicklistEntry.isDefaultValue(),
                        'label' => tPicklistEntry.getLabel()
                    });*/
                }
            } else {
                //TODO 不存在此字段的执行
            }
        } else {
            // TODO 不存在此sObject的执行
        }
        return picValues;
    }
      ///获取当前 或者 上年的合同产品
    private String getContractProduct(Id conid ,Boolean islastYear){

		Schema.DescribeSobjectResult m = ContractProduct__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();
        cpbList.clear();
        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;
        sql += ' ,Product__r.Name,Product__r.Category1__c, Product__r.NCCode__c,Product__r.zl__c,Product__r.TypeName__c,Product__r.PriceCompany__c ';
        sql += ',Product__r.Category0__c,Product__r.Category2__c,Product__r.Category3__c,Product__r.Brand__c';
        sql += ',Product__r.BrandShort__c,Product__r.Unit__c,Product__r.Spec__c,Product__r.Model__c,Product__r.SerialNo__c ';
        sql += 'from ContractProduct__c where Contract__c = \'' + conid + '\'';
        Set<Id> pids = new Set<Id>();
        System.debug('+++'+conid);
        List<ContractProduct__c> cpList = Database.query(sql);
        for (ContractProduct__c cp : cpList) {
        	pids.add(cp.Product__c);
        }
        Map<Id, Price__c> priceMap = getPriceMap(pids);
         for (ContractProduct__c cp : cpList) {

        	cpbList.add(new ContractProductBean(cp,priceMap.get(cp.Product__c),islastYear));
        }

         return EncodingUtil.urlEncode(JSON.serialize(cpbList), 'UTF-8');
  
    }

    public void getSystemContractProduct(){
        productListJson = getContractProduct(parentCon.Id ,false);
    }
    
    ///检索产品 并带出价格
     public void search() {
         pbList.clear();
        String whereStr = '';
        List<Product__c> plist = new List<Product__c>();
        if (String.isBlank(name) == false) {
            whereStr += ' and Name like \'%' + name + '%\'';
        }
        if (String.isBlank(brand) == false) {
            whereStr += ' and  Brand__c like \'%' + brand + '%\'';
        }
        if (String.isBlank(serial) == false) {
            whereStr += ' and  SerialNo__c like \'%' + serial + '%\'';
        }
        if (String.isBlank(category0) == false) {
            whereStr += ' and  Category0__c = \'' + category0 + '\'';
        }
        if (String.isBlank(category1) == false) {
            whereStr += ' and  Category1__c = \'' + category1 + '\'';
        }
         if (String.isBlank(typeName) == false) {
            whereStr += ' and  TypeName__c like \'%' + typeName + '%\'';
        }
               
        plist = Database.query(this.soqlStr() + whereStr + ' limit 300');
       // 获取价格信息
        Set<Id> pidList = new Set<Id>();
        for (Product__c p : plist) {
            if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag)))pidList.add(p.Id);
        }
        Map<Id, Price__c> priceMap = getPriceMap(pidList);
        List<ContractProductBean>  temp= new List<ContractProductBean>();
        for (Product__c p : plist) {
            if(priceMap.get(p.Id) == null)continue;
            pbList.add(new ProductBean(p, priceMap.get(p.Id)));
            if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag)))temp.add(new ContractProductBean(p,priceMap.get(p.Id)));
        }
                        

         productListJson = EncodingUtil.urlEncode(JSON.serialize(temp), 'UTF-8');
        
    }
     private String soqlStr() {
        Schema.DescribeSobjectResult m = Product__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();
        
        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;
        sql += ' from Product__c where Name != null  and  PriceCompany__c  like \'%' +concode+ '%\' ';

        return sql;
    }
      
///获取价格
  private Map<Id,Price__c> getPriceMap(Set<Id> pids){
  Map<Id, Price__c> priceMap = new Map<Id, Price__c>();
            for (Price__c pr : [select Id, Product__c,Product__r.bggsjhdj__c, MarketPrice__c, HospitalManagerPrice__c, HospitalBottomPrice__c, CompanyBottomPrice__c,
                AreaDealerPrice__c, InvoiceDealerPrice__c, RepairCost__c, InstCost__c ,LastMonthAveragePrice__c,Taxrate__c  
                                from Price__c where Product__c in : pids and Company__c = :u.SubCompany__c]) {
                priceMap.put(pr.Product__c, pr);
            }
      return priceMap;
  
  }
  ///获取分支机构总公司价
    private Map<Id,Decimal> getSystemPrice(Set<Id>pids){
        
        Map<Id,Decimal>priceMap = new Map<Id,Decimal>();
        if(parentCon == null)return priceMap;

        for (ContractProduct__c cp : [select Id,SalesPrice__c,Product__c  from ContractProduct__c where 
            Contract__c =:parentCon.Id and DelContractProduct__c != true]) {
            priceMap.put(cp.Product__c,cp.SalesPrice__c);
        }
        return priceMap;

    }
    ////获取上月平均价
  private Map<Id,AveragePrice__c> getAveragePriceMap(Set<Id> pids){
           /// 日期处理
                Integer m = Date.today().month(); //当前月份
                Integer y = Date.today().year();  //当前年份 
               ///取上月
                 if(m == 1){
                m = 12 ;
                    y -= 1;
                }else{
                m -= 1;

                }

                String  month = String.valueOf(m) + '月';
                String  year= String.valueOf(y) + '年';
            ///获取上月平均价
            Map<Id,AveragePrice__c>aPriceMap = new Map<Id,AveragePrice__c>();
            for(AveragePrice__c a :[select Id ,AveragePrice__c,Product__c from AveragePrice__c 
                                    where Product__c in : pids and Company__c = :u.SubCompany__c and Year__c =:year and Month__c =:month]){
            aPriceMap.put(a.Product__c,a);
            }
      return aPriceMap;
  }

  public void saveres(){
  
    msg = '';
    List<Object> os = (List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(resJson,'UTF-8')) ;
                        System.debug(os);

     
      Set<Id> pIdList = new Set<Id>();

     for ( Object o : os) {
            Map<String ,Object> res = (Map<String ,Object> )o ;
             if(res.get('productId') == null)continue;

            Id productId = Id.valueOf(String.valueOf(res.get('productId')));
            String c = String.valueOf(res.get('hasPrice'));
            System.debug(c +'==='+corpcode);
            if(c == null )c = '';
            if(c.contains(corpcode)){
                pIdList.add(productId);
            }else{

                msg += '<p>'+res.get('name')+'--'+res.get('spec')+'--'+res.get('serialNo')+'</p>';
            }
      }
      if(msg.length() > 0){
            isSuccess = false;
            msg = '<h1>这些产品没有价格体系:</h1>'+msg;
            return ;
      }
      List<ContractProduct__c> resList = new List<ContractProduct__c>();
      Map<Id,Price__c> priceMap = getPriceMap(pIdList);
      Map<Id,Decimal> systemMap = getSystemPrice(pIdList);
      System.debug('==='+ systemMap);
     Id rt = Utils.getRecordTypeIdByDevNameAndObjName('ContractCommodityProduct','ContractProduct__c');
     try{

        for ( Object o : os) {
              Map<String ,Object> res = (Map<String ,Object> )o ;
                ContractProduct__c cp = new ContractProduct__c();
                if(res.get('productId') == null)continue;
                Id productId = Id.valueOf(String.valueOf(res.get('productId')));

                cp.Name = String.valueOf(res.get('name'));
                cp.AreaDealerPrice__c = priceMap.containsKey(productId) ? priceMap.get(productId).AreaDealerPrice__c : null;
                cp.InvoiceDealerPrice__c = priceMap.containsKey(productId) ? priceMap.get(productId).InvoiceDealerPrice__c : null;
               
                 ///成本价
                cp.InstCost__c = priceMap.containsKey(productId) ? priceMap.get(productId).InstCost__c : null;
                
                cp.UnitPrice1__c = priceMap.containsKey(productId) ? priceMap.get(productId).MarketPrice__c : null;//市场报价
                
                cp.SalesPrice__c =  Decimal.valueOf(String.valueOf(res.get('salesPrice')));///售价
         
                cp.Product__c = productId;
               if(res.get('lastYearSalesPrice')!= null) cp.LastYearSalesPrice__c = Decimal.valueOf(String.valueOf(res.get('lastYearSalesPrice')));

                cp.DiscountRate__c = (res.get('discountRate')!= null) ? Decimal.valueOf(String.valueOf(res.get('discountRate'))):0;
     
                if(res.get('taxRate')!= null)cp.Taxrate__c = Decimal.valueOf(String.valueOf(res.get('taxRate')));
                cp.Contract__c = con.Id;
                cp.ProductLine__c = String.valueOf(res.get('category1'));
                cp.SystemPrice__c = systemMap.containsKey(productId) ? systemMap.get(productId) : null;
                cp.RecordTypeId = rt; 
                resList.add(cp);

         } 

     }catch(Exception e){
            msg = '数据处理出错'+e.getMessage();
            isSuccess = false;
            return ;
     }
     if(resList.size() > 0){
        Savepoint sp = Database.setSavepoint();
         try {
             // 合同产品delete
            List<ContractProduct__c> delList = [select Id from ContractProduct__c where Contract__c = :cId];
            if (delList.size() > 0) delete delList;

            insert resList;
            isSuccess = true;
            msg = '保存成功!';
         }catch (Exception e) {
            Database.rollback(sp);
             msg = '数据处理出错'+e.getMessage();
            isSuccess = false;
            return ;
         } 
     }else{
             msg = '没有数据!请选择产品!';
            isSuccess = false;
            return ;
     }
     

  }
  
   
    /* public void exchange() {
        // 去掉已勾选的合同产品
        Set<Id> existPid = new Set<Id>();
        List<ContractProductBean> stayList = new List<ContractProductBean>();
        for (ContractProductBean qpb : cpbList) {
            if (qpb.chk == false) {
                stayList.add(qpb);
                existPid.add(qpb.productId);

            }
        }
        cpbList.clear();
        cpbList.addAll(stayList);
 
         
        // 加入已勾选的产品
        for (ProductBean p : pbList) {
            if (p.chk == true && existPid.contains(p.rec.Id) == false) {
                cpbList.add(new ContractProductBean(p.rec,p.pr));
                p.chk = false;
            }
        }
        // tempCategoryOpt(cpbList);

    }
    */

    /*
    ///删除操作
    public void deleteOption(){
        isOption = false;
        List<ContractProductBean> tList = new List<ContractProductBean>();
        tList.addAll(cpbList);
        Map<Id,Id> deleteID = new Map<Id,Id>();
    for(ContractProductBean pb : tempList){
            if(pb.chk == true){
               deleteID.put(pb.productId,pb.productId);
             }
            
         }
        cpbList.clear();
	for(ContractProductBean qpb : tList){
         if(deleteID.containskey(qpb.productId)){
         	continue;
         }else{
         	cpbList.add(qpb);
         }
                            
     }  
       tempCategoryOpt(cpbList);

    }
     
    ///保存更新操作
    public void saveOption(){
        isOption = false;
        List<ContractProductBean> tList = new List<ContractProductBean>();
        tList.addAll(cpbList);
        Map<Id,ContractProductBean> updateqpb = new Map<Id,ContractProductBean>();
    	for(ContractProductBean pb : tempList){
               updateqpb.put(pb.productId,pb);            
         }
        cpbList.clear();
		for(ContractProductBean qpb : tList){
             if(updateqpb.containskey(qpb.productId)){
             	cpbList.add(updateqpb.get(qpb.productId));
             }else{
             	cpbList.add(qpb);
             }
                            
         } 
         tempCategoryOpt(cpbList);

    }
   public void cancelOption(){
        isOption = false;
        tempList.clear();
       tempCategoryOpt(cpbList);
   }
	public void shaixuan(){
		System.debug('===' + tempName+'\t'+ tempCategory1+'\t'+ tempCategory2+'\t' + tempBrand+'\t'+ tempTypeName+'\t');
        isOption = true;
    	tempList.clear();
        Map<Id,ContractProductBean> temp = new Map<Id,ContractProductBean>();
        ///名称
        if(String.isBlank(tempName) == false){
        for(ContractProductBean pb : cpbList){
            if(pb.name.contains(tempName)){
                temp.put(pb.productId ,pb);
                }            
            }
        }else{
        temp = setTempMap();
        }
        ///一级分类
        Map<Id,ContractProductBean> temp1 = new Map<Id,ContractProductBean>();
        if(String.isBlank(tempCategory1) == false){
           if(temp.size() == 0)temp = setTempMap();

        for(ContractProductBean pb : temp.values()){
            if(pb.category1.contains(tempCategory1)){
                temp1.put(pb.productId ,pb);
                }
            
            }
        }else{
        temp1 = temp;
        }

        ///二级分类
        Map<Id,ContractProductBean> temp2 = new Map<Id,ContractProductBean>();
        if(String.isBlank(tempCategory2) == false){
       if(temp1.size() == 0)temp1 = setTempMap();
        for(ContractProductBean pb : temp1.values()){
            if(pb.category2.contains(tempCategory2)){
                temp2.put(pb.productId ,pb);
                }
            
            }
        }else{
        temp2 = temp1;
        }
        //品牌
        Map<Id,ContractProductBean> temp3 = new Map<Id,ContractProductBean>();
        if(String.isBlank(tempBrand) == false){
       if(temp2.size() == 0)temp2 = setTempMap();
        for(ContractProductBean pb : temp2.values()){
            if(pb.brand.contains(tempBrand) || pb.brandS.contains(tempBrand)  ){
                temp3.put(pb.productId ,pb);
                }
            }
        }else{
        temp3 = temp2;
        }
        ///产品结构
    	 Map<Id,ContractProductBean> temp4 = new Map<Id,ContractProductBean>();
        if(String.isBlank(tempTypeName) == false){
       if(temp3.size() == 0)temp3 = setTempMap();
        for(ContractProductBean pb : temp3.values()){
            if(pb.typeName.contains(tempTypeName) ){
                temp4.put(pb.productId ,pb);
                }
            }
        }else{
        temp4 = temp3;
        }
    
        tempList.addAll(temp4.values());
        
for(ContractProductBean qpb:tempList){
        qpb.chk = true;
        }
        ///设置分类下拉框
       tempCategoryOpt(tempList);
        
    }
    private void tempCategoryOpt(List<ContractProductBean> qbList){
     ///选项列表
        Set<String> c1 = new Set<String>();
        Set<String> c2 = new Set<String>();
	for(ContractProductBean qpb:qbList){
		if(qpb.category1 !=null && qpb.category1 != '')c1.add(qpb.category1);
		if(qpb.category2 !=null && qpb.category2 != '')c2.add(qpb.category2);
    }
      tempCategory1opts = optionHandler(c1);
      tempCategory2opts = optionHandler(c2);
    }
    ///设置选项列表
      private List<SelectOption>  optionHandler (Set<String> s){
       List<SelectOption> ss = new List<SelectOption>();
       ss.add(new SelectOption('', System.Label.Option_None));

        for (String str : s){
        ss.add(new SelectOption(str,str));
        }
        return ss;
    }
    ///
    public Map<Id,ContractProductBean> setTempMap() {
        Map<Id,ContractProductBean> temp = new Map<Id,ContractProductBean>();
    	for(ContractProductBean qb: cpbList){
        	temp.put(qb.productId,qb);
        }
        return temp;
    }
    */
     public class ContractProductBean {
        public String name { get; set; }
        public String serialNo { get; set; }
        public String ncCode { get; set; }
        public String spec { get; set; }
        public String brand { get; set; }
        public String brandS { get; set; }
        public String unit { get; set; }
        public String model { get; set; }
        /*public String sNameEng { get; set; }
        public String fnameEng { get; set; }
        public String fNameChs { get; set; }*/
        public String quantity { get; set; }
        public String category0 { get; set; }
        public String category1 { get; set; }
        public String category2 { get; set; }
        public String category3 { get; set; }
        public String category4 { get; set; }
        public Decimal marketPrice { get; set; }///市场报价
        public Decimal discountRate { get; set; }
        public Decimal salesPrice { get; set; } /// 售价
        public String comment { get; set; }
        public Id productId { get; set; }
        public Boolean chk { get; set; }
        public Decimal invoiceDealerPrice {get;set;}//报单经销商价
        //public QuoteProduct__c qp {get;set;}//报价产品
        public Decimal taxRate {get;set;}//税率
        public Decimal lastYearSalesPrice {get;set;}//去年售价
        public Decimal zl {get;set;}//装量
        public String typeName {get;set;}//产品类型
        public String productline {get;set;}//产品线
        public String hasPrice {get;set;}///有价格体系的公司
       
        public ContractProductBean() {}
		///匹配数字
        private Decimal matchNumber(String str){
            if(str == null)return 0;
            Matcher m1 =  Pattern.compile('([1-9]([0-9]*)(\\.[0-9]+)?)|(^0$)').matcher(str);
            m1.find();
            try{
                String res = m1.group();
                return Decimal.valueOf(res);
            }catch(Exception e){
                return 0;
            }
        }
      
     	public ContractProductBean(ContractProduct__c cp,Price__c pr,Boolean islastYear) {
            name = cp.Product__r.Name;
            serialNo = cp.Product__r.SerialNo__c;
            ncCode = cp.Product__r.NCCode__c;
            spec = cp.Product__r.Spec__c;
            brand = cp.Product__r.Brand__c;
            brandS = cp.Product__r.BrandShort__c;
            unit = cp.Product__r.Unit__c;
            model = cp.Product__r.Model__c;
          
            category0 = cp.Product__r.Category0__c;
            category1 = cp.Product__r.Category1__c;
            category2 = cp.Product__r.Category2__c;
            category3 = cp.Product__r.Category3__c;
            productId = cp.Product__c;
            salesPrice = cp.SalesPrice__c;
            lastYearSalesPrice = islastYear== true ? cp.SalesPrice__c:cp.LastYearSalesPrice__c; ///售价带过来
            //lastYearSalesPrice = 111;
            zl = matchNumber(cp.Product__r.zl__c);//装量
            hasPrice = cp.Product__r.PriceCompany__c;
            chk = false;
            comment = null;
           	typeName = cp.Product__r.TypeName__c;
            productline = cp.ProductLine__c;
            if(pr != null) {
                    marketPrice = pr.MarketPrice__c;
                    taxRate = pr.Taxrate__c;
                    invoiceDealerPrice = pr.InvoiceDealerPrice__c;
            }
             discountRate =  (marketPrice != null && marketPrice != 0 && salesPrice != null && salesPrice != 0)? ((marketPrice - salesPrice) / marketPrice * 100).setScale(2, RoundingMode.HALF_UP): cp.DiscountRate__c;


                
          }

          public ContractProductBean(Product__c record,Price__c pr) {
            name = record.Name;
            serialNo = record.SerialNo__c;
            ncCode = record.NCCode__c;
            spec = record.Spec__c;
            brand = record.Brand__c;
            brandS = record.BrandShort__c;
            unit = record.Unit__c;
            model = record.Model__c;
        
            category0 = record.Category0__c;
            category1 = record.Category1__c;
            category2 = record.Category2__c;
            category3 = record.Category3__c;
             typeName = record.TypeName__c;
             hasPrice = record.PriceCompany__c;
            productline = record.Category1__c;
            comment = null;
            if(pr != null) {
                marketPrice = pr.MarketPrice__c;
                 taxRate = pr.Taxrate__c;
                invoiceDealerPrice = pr.InvoiceDealerPrice__c;
            }
            productId = record.Id;
            chk = false;
            zl = matchNumber(record.zl__c);//装量
        }
     }
        
    public class ProductBean {
		public Product__c rec { get; set; }
        public Price__c pr { get; set; }
        public Boolean chk { get; set; }

        public ProductBean(Product__c record, Price__c price) {
            rec = record;
            pr = price;
            chk = false;
        }
    }
    public class PriceBean{
    	public Id rec { get; set; }//产品
        public Price__c pr { get; set; }//价格
        public AveragePrice__c avpr {get;set;}//月平均价
    }
}